import {Utils} from './common.js'

const Side = Object.freeze({
    LEFT: 1,
    RIGHT: 2,
    TOP: 3,
    BOTTOM: 4,
});

const _BORDER_THICKNESS = 8;// px;

function _CreateDraggableHTMLText(side) {
    let _style = "";
    switch(side) {
        case Side.LEFT:
            break;
        case Side.TOP:
            break;
        case Side.BOTTOM:
            _style = `height:${_BORDER_THICKNESS}px;left:0px;bottom:-${_BORDER_THICKNESS * 0.5}px;width:100%;cursor:row-resize`;
            break;
        case Side.RIGHT:
        default:
            _style = `height:100%;right:-${_BORDER_THICKNESS * 1.5}px;top:0px;width:${_BORDER_THICKNESS}px;cursor:col-resize`;
            break;
    }
    _style += ';position:absolute';
    return `<div style="${_style}"> <div style="position: relative;bottom: -50vh; opacity:0.3; left:-4px;" class="bi bi-grip-vertical"> </div></div>`;
}

let _x = 0;
let _y = 0;

function RegistElementResizable(target, side, enabled = true) {
    if(!target) return undefined;

    let _enabled = false;
    let _w = 0;
    let _h = 0;
    const _draggerElem = Utils.CreateHTMLElement(_CreateDraggableHTMLText(side));

    const mouseDownHandler = function (e) {
        _x = e.clientX;
        _y = e.clientY;

        _w = parseInt(target.offsetWidth, 10);
        _h = parseInt(target.offsetHeight, 10);

        // Attach the listeners to `document`
        document.addEventListener('mousemove', mouseMoveHandler);
        document.addEventListener('mouseup', mouseUpHandler);
        target.style.userSelect = 'none';
    };

    const mouseMoveHandler = function (e) {
        const dx = e.clientX - _x;
        const dy = e.clientY - _y;

        if(side < Side.TOP) {
            target.style.width = `${_w + dx}px`;
        } else {
            target.style.height = `${_h + dy}px`;
        }
        e.stopImmediatePropagation();
    };

    const mouseUpHandler = function () {
        document.removeEventListener('mousemove', mouseMoveHandler);
        document.removeEventListener('mouseup', mouseUpHandler);
        target.style.userSelect = 'auto';
    };

    const Enable = function () {
        if(!_enabled) {
            target.append(_draggerElem);
            _draggerElem.addEventListener('mousedown', mouseDownHandler);
            _enabled = true;
        }
    }
    const Disable = function () {
        if(_enabled) {
            _draggerElem.remove();
            _draggerElem.removeEventListener('mousedown', mouseDownHandler);
            _enabled = false;
        }
    }
    if(enabled) {
        Enable();
    }
    return {Enable, Disable};
}

export default {RegistElementResizable, Side};
